import { SharedMethodService } from './../../../@core/services/Sharedmethod/shared-method.service';
import { DirctoryService } from './../../../@core/services/dirctory/dirctory.service';
import { Component, ElementRef, ViewChild } from '@angular/core';
import { DataTableComponent, DialogService, TableWidthConfig, TreeComponent } from 'ng-devui';
import { AddDirctoryTypeComponent } from './add-dirctory-type/add-dirctory-type.component';
import { EditDirctoryTypeComponent } from './edit-dirctory-type/edit-dirctory-type.component';
import { AddDirctoryComponent } from './add-dirctory/add-dirctory.component';
import { EditDirctoryComponent } from './edit-dirctory/edit-dirctory.component';
@Component({
  selector: 'app-dirctory',
  templateUrl: './dirctory.component.html',
  styleUrls: ['./dirctory.component.scss']
})
export class DirctoryComponent {
  pager = {
    total: 20,
    pageIndex: 1,
    pageSize: 20
  };
  pageSizeOptions = [10, 20, 30, 50, 100];
  treeData:any;
  categoryId!:string
  dirctorData:any;
  allCheckedStatus = false;
  checkedIds = [];
  option:any;//字典类别option
  pathPids:any//字典类被路径
  checkboxList = [];
  allChecked = false;
  halfChecked = false;
  dataTableOptions = {
    columns: [
      {
        field: 'name',
        header: '名称',
        fieldType: 'text'
      },
      {
        field: 'value',
        header: '值',
        fieldType: 'text'
      },
      {
        field: 'description',
        header: '描述',
        fieldType: 'boolean'
      }
    ]
  };//表头数据
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: 'checkbox',
      width: '80px'
    },
    {
      field:'name',
      width:'250px'
    },
    {
      field: 'value',
      width: '150px'
    },
    {
      field: 'description',
      width: '250px'
    }
  ];//表格宽度配置
  msgs: Array<Object> = [];
  searchDirctoryValue:any=''
  @ViewChild('basicTree', { static: true }) basicTree!: TreeComponent;
  @ViewChild(DataTableComponent, { static: true }) datatable: DataTableComponent;
  filteredTreeNodes: any[];
  displayTreeData: any[];
  constructor(private DirctoryService:DirctoryService,private dialogService: DialogService,private SharedMethodService:SharedMethodService){}
  ngOnInit(): void {
    this.DirctoryService.getDictionaryType(this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
      this.treeData=data?.items;
      this.addOpenProperty(this.treeData);
      this.displayTreeData = this.treeData;
      this.displayTreeData = [{ name: '全部',categoryId:null}, ...this.treeData];

      if(this.treeData.length>0){
        this.option=this.treeData[0]
        this.categoryId = this.treeData[0].categoryId
        this.DirctoryService.getDictionary(this.pager.pageIndex,this.pager.pageSize,this.categoryId).subscribe((data:any)=>{
          this.dirctorData=data.items;
          this.pager.total=data.totalCount;

        })
      }
      this.pager.total=data?.totalCount;
      if (this.categoryId !== undefined) {
        this.DirctoryService.getDictionary(this.pager.pageIndex,this.pager.pageSize,this.categoryId).subscribe((data:any)=>{
          this.dirctorData=data.items;
          this.pager.total=data.totalCount;
        })
      }
    })
  }
  nodeSelected($event:any){
    this.option=$event.data.originItem
    this.categoryId = $event.data.originItem.categoryId;
    this.DirctoryService.getDictionary(this.pager.pageIndex,this.pager.pageSize,this.categoryId).subscribe((data:any)=>{
      this.dirctorData=data.items;
      this.pager.total=data.totalCount;
    })
    for(let node of  this.treeData){
      console.log(node,this.categoryId,this.treeData)
      const path = this.getPathPids(node, this.categoryId);
      if(path){
        this.pathPids = path;
        break;
      }else{
        this.pathPids = []
      }

    }
   console.log(this.pathPids)
  }//树形菜单点击事件
  config = {
    id: 'Add-Dirctoy-Type',
    maxHeight: '400px',
    width: '400px',
    backdropCloseable: true,
  }//弹窗配置
  addDirctoyType(dialogtype?: string) {
    let data = {
      options: this.treeData,
      pathPids: this.pathPids && this.pathPids[0] !== null ? this.pathPids : [],
      display: false
    };
    const results = this.dialogService.open({
      ...this.config,
      title: '新增字典类别',
      content: AddDirctoryTypeComponent,
      dialogtype: dialogtype,
      onClose: () => {

      },
      data:data,
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if(results.modalContentInstance.PostDictionaryType.name){
              this.DirctoryService.postDictionaryType(results.modalContentInstance.PostDictionaryType).subscribe((data:any)=>{
                this.showToast('success','成功','字典类别添加成功！')
                results.modalInstance.hide();
                this.DirctoryService.getDictionaryType(this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
                  this.treeData=data.items;
                  this.displayTreeData = this.treeData;
                  this.pager.total=data.totalCount;
                  this.displayTreeData = [{ name: '全部',categoryId:null}, ...this.treeData];
                })
              },(error: any) => {
                if (error.status === 404) {
                  this.showToast('error', '错误', '网络连接错误');
                } else {
                  this.showToast('error', '错误', error.error);
                }
                results.modalInstance.hide();
              }
              )
            }else{
              data.display = true;
            }
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }//新增字典类别
  EditDirctoyType(dialogtype?: string) {
    let data = {
      options: this.treeData,
      pathPids: this.pathPids,
      display: false,
      option:this.option
    };
    const results = this.dialogService.open({
      ...this.config,
      title: '更新字典类别',
      content: EditDirctoryTypeComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      data:data,
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if(results.modalContentInstance.PutDictionaryType.name){
              this.DirctoryService.putDictionaryType(this.categoryId,results.modalContentInstance.PutDictionaryType).subscribe((data:any)=>{
                this.showToast('success','成功','字典类别修改成功！')
                results.modalInstance.hide();
                this.DirctoryService.getDictionaryType(this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
                  this.treeData=data.items;
                  this.displayTreeData = this.treeData;
                  this.pager.total=data.totalCount;
                  this.displayTreeData = [{ name: '全部',categoryId:null}, ...this.treeData];
                })

              },(error: any) => {
                if (error.status === 404) {
                  this.showToast('error', '错误', '网络连接错误');
                } else {
                  this.showToast('error', '错误', error.error);
                }
                results.modalInstance.hide();
              }
              )
            }else{
              data.display = true;
            }
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }//更新字典类别
  DeleteDirctoyType(dialogtype?: string){
    const results = this.dialogService.open({
      ...this.config,
      title: '删除字典类别',
      content: '确认删除该字典类别？',
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.DirctoryService.deleteDictionaryType(this.categoryId).subscribe((data:any)=>{
              this.showToast('success','成功','字典类别删除成功！')
              results.modalInstance.hide();
              this.DirctoryService.getDictionaryType(this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
                this.treeData=data.items;
                this.displayTreeData = this.treeData;
                this.pager.total=data.totalCount;
                this.displayTreeData = [{ name: '全部',categoryId:null}, ...this.treeData];
              })
            },(error: any) => {
              if (error.status === 404) {
                this.showToast('error', '错误', '网络连接错误');
              } else {
                this.showToast('error', '错误', error.error);
              }
              results.modalInstance.hide();
            }
            )
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }//删除字典类别
  addDirctoy(dialogtype?: string) {
    let data = {
      options: this.treeData,
      pathPids: this.pathPids,
      display: false
    };
    const results = this.dialogService.open({
      ...this.config,
      title: '新增字典',
      content: AddDirctoryComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      data:data,
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if(results.modalContentInstance.PostDictionary.entryName&&results.modalContentInstance.PostDictionary.entryValue){
              this.DirctoryService.postDictionary(results.modalContentInstance.PostDictionary).subscribe((data:any)=>{
                this.showToast('success','成功','字典添加成功！')
                results.modalInstance.hide();
                this.DirctoryService.getDictionary(this.pager.pageIndex,this.pager.pageSize,this.categoryId).subscribe((data:any)=>{
                  this.dirctorData=data.items;
                  this.pager.total=data.totalCount;
                })
              },(error: any) => {
                if (error.status === 404) {
                  this.showToast('error', '错误', '网络连接错误');
                } else {
                  this.showToast('error', '错误', error.error);
                }
              }
              )
            }else{
              data.display = true;
            }
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }//新增字典
  editDirctoy(dictionary:any,dialogtype?: string) {
    let data = {
      options: this.treeData,
      pathPids: this.pathPids,
      display: false,
      dictionary:dictionary
    };
    const results = this.dialogService.open({
      ...this.config,
      title: '更新字典',

      content: EditDirctoryComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      data:data,
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if(results.modalContentInstance.PutDictionary.entryName&&results.modalContentInstance.PutDictionary.entryValue){
              this.DirctoryService.putDictionary(dictionary?.dictionaryEntryId,results.modalContentInstance.PutDictionary).subscribe((data:any)=>{
                this.showToast('success','成功','字典更新成功！')
                results.modalInstance.hide();
                this.DirctoryService.getDictionary(this.pager.pageIndex,this.pager.pageSize,this.categoryId).subscribe((data:any)=>{
                  this.dirctorData=data.items;
                  this.pager.total=data.totalCount;
                })
              },(error: any) => {
                if (error.status === 404) {
                  this.showToast('error', '错误', '网络连接错误');
                } else {
                  this.showToast('error', '错误', error.error);
                }
              }
              )
            }else{
              data.display = true;
            }
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }//更新字典
  deleteDirctoy(dialogtype?: string){
    const results = this.dialogService.open({
      ...this.config,
      title: '删除字典',
      content: '确认删除该字典？',
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.DirctoryService.deleteDictionary(this.checkedIds).subscribe((data:any)=>{
              this.showToast('success','成功','字典删除成功！')
              this.checkedIds=[]
              results.modalInstance.hide();
              this.DirctoryService.getDictionary(this.pager.pageIndex,this.pager.pageSize,this.categoryId).subscribe((data:any)=>{
                this.dirctorData=data.items;
                this.pager.total=data.totalCount;
              })
            },(error: any) => {
              if (error.status === 404) {
                this.showToast('error', '错误', '网络连接错误');
              } else {
                this.showToast('error', '错误', error.error);
              }
            }
            )
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }//删除字典

  getPathPids(node: { categoryId: any; subCategories: any; }, targetId: any, path = []) {
    if (node.categoryId === targetId) {
      return [...path, node.categoryId];
    }
    if (node.subCategories) {
      for (let subNode of node.subCategories) {
        const subPath = this.getPathPids(subNode, targetId, [...path, node.categoryId]);
        if (subPath) {
          return subPath;
        }
      }
    }
    return null;
  } //获取树形菜单pid的路径
  showToast(type: any,summary:any,content:any) {
    switch (type) {
    default:
      this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  afterTreeInit($event: any){
    if($event["1"]){
      $event["1"].data.isActive=true
    }
  }//树形菜单初始化
  pageIndexChange($event: any) {
    this.pager.pageIndex=$event;
    this.DirctoryService.getDictionary(this.pager.pageIndex,this.pager.pageSize,this.categoryId).subscribe((data:any)=>{
      this.dirctorData=data.items;
      this.pager.total=data.totalCount;
    })
  }//切换页码
  pageSizeChange($event: any){
    this.DirctoryService.getDictionary(this.pager.pageIndex,this.pager.pageSize,this.categoryId).subscribe((data:any)=>{
      this.dirctorData=data.items;
      this.pager.total=data.totalCount;
    })
  }//改变每页显示数量
  searchDepartment($event: any) {
    this.searchDirctoryValue = $event.target.value;
    this.displayTreeData = this.filterNodes(this.treeData, this.searchDirctoryValue)

  }//搜索
  filterNodes(nodes: any, searchTerm: any) {
    let result = [];
    for (let node of nodes) {
      // 如果节点的 name 属性包含搜索词，将整个节点添加到结果中
      if (node.name.includes(searchTerm)) {
        result.push(node);
      } else if (node.subCategories) {
        node.open = true;
        // 否则，如果节点有 subCategories 属性，递归过滤 subCategories
        let filteredSubCategories = this.filterNodes(node.subCategories, searchTerm);
        if (filteredSubCategories.length > 0) {
          // 如果有任何 subCategories 符合条件，创建一个新的节点，其 subCategories 是过滤后的结果
          let newNode = { ...node, subCategories: filteredSubCategories };
          result.push(newNode);
        }
      }
    }
    return result;
  }
  addOpenProperty(nodes) {
    for (let node of nodes) {
      if (node.subCategories) {
        node.open = true;
        this.addOpenProperty(node.subCategories);
      }
    }
  }//添加open属性默认展开
  onRowCheckChange(checked: any, rowIndex: any, nestedIndex: any, rowItem: { $checked: any; $halfChecked: boolean; }){
    this.SharedMethodService.onRowCheckChange(checked, rowIndex, nestedIndex, rowItem,this.datatable)
  }
  getCheckedRows() {
    this.SharedMethodService.getCheckedRows(this.datatable,'dictionaryEntryId').subscribe((data:any)=>{
      this.checkedIds=data;
    })
  }//获取选中行
  cleared(){
    this.SharedMethodService.cleared(this.checkedIds,this.dirctorData,this.datatable).subscribe((data:any)=>{
      this.checkedIds=data;
    })
  }
}
